package javaTest05.exercise02.client;

import com.alibaba.fastjson.JSON;
import javaTest05.exercise02.dto.MessageDto;
import javaTest05.exercise02.dto.MsgType;
import javaTest05.utils.LogUtils;
import javaTest05.utils.SocketUtils;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ClientSendHandler implements Runnable {

    private Scanner in = new Scanner(System.in);

    private Socket socket;

    private DataOutputStream send;

    private String hostName;

    private boolean flag = true;

    public ClientSendHandler(Socket socket) throws IOException {
        this.socket = socket;
        this.send = new DataOutputStream(socket.getOutputStream());
        LogUtils.info("客户端发信线程已建立...");
    }

    @Override
    public void run() {

        try {
            login();

            while (flag) {
                String msg = in.nextLine();

                String receiver = null;
                MsgType type = MsgType.Group_Msg;

                if (msg.equals(SocketUtils.QUIT_FLAG)) {//如果输入退出标志 则退出,线程结束
                    this.flag = false;
                    LogUtils.info("已退出,客户端关闭");
                    break;
                }

                if (msg.contains(SocketUtils.TO_FLAG)) {
                    int index = msg.lastIndexOf(SocketUtils.TO_FLAG);
                    receiver = msg.substring(index + SocketUtils.TO_FLAG.length());
                    msg = msg.substring(0, index);
                    type = MsgType.Private_Msg;
                }

                MessageDto messageDto = new MessageDto(hostName, receiver, type);
                messageDto.setStatus(true);
                messageDto.setMsg(msg);

                LogUtils.say(messageDto);

                sendMsg(messageDto);
            }
        } catch (Exception e) {
            LogUtils.error("消息传输异常,请重新连接");
        } finally {
            SocketUtils.close(send, socket);
        }

    }

    private void login() throws IOException {
        LogUtils.info("请输入你的用户名,或者输入wq!退出");
        hostName = in.nextLine();
        if (hostName.equals(SocketUtils.QUIT_FLAG)) {
            this.flag = false;
            LogUtils.info("已退出");
        } else {
            LogUtils.info("登陆成功,你的用户名为: " + hostName);
            MessageDto messageDto = new MessageDto(hostName, null, MsgType.Register);
            messageDto.setMsg(hostName);
            messageDto.setStatus(true);

            sendMsg(messageDto);
        }
    }

    private void sendMsg(MessageDto messageDto) throws IOException {
        send.writeUTF(JSON.toJSONString(messageDto));
        send.flush();
    }
}
